package com.sinoglobal.dumping.activity;

import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.FileProvider;
import android.support.v4.content.Loader;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;

import com.sinoglobal.dumping.R;
import com.sinoglobal.dumping.adapter.Dumpling_PhotosSeletorAdapter;
import com.sinoglobal.dumping.base.Dumpling_SinoBaseActivity;
import com.sinoglobal.dumping.base.Dumpling_SinoConstans;
import com.sinoglobal.dumping.util.Dumpling_FileUtils;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.util.ArrayList;

/**
 * 图片选择
 */
public class Dumpling_PhotosSelectorActivity extends Dumpling_SinoBaseActivity implements LoaderManager.LoaderCallbacks<Cursor> {
    private static final int CAPTURE_PHOTO_RESULT_CODE = 10;
    private static final int CAPTURE_PHOTO_REQUEST_CODE = 100;
    private static final int CAPTURE_CAMERA_REQUEST_CODE = 101;
    private static final String[] STORE_IMAGES = {MediaStore.Images.Media.DATA, MediaStore.Images.Media.DISPLAY_NAME, MediaStore.Images.Media.DATE_ADDED, MediaStore.Images.Media._ID};
    private GridView imageGrid;
    private Dumpling_PhotosSeletorAdapter seletorAdapter;
    private File imageFile;
    private int imageWidth;
    private int imageHeight;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dumpling_activity_photos_selector);
        imageWidth = getIntent().getIntExtra("imageWidth", 300);
        imageHeight = getIntent().getIntExtra("imageHeight", 200);
        imageGrid = (GridView) findViewById(R.id.dumpling_card_photo_seletor);
        seletorAdapter = new Dumpling_PhotosSeletorAdapter(Dumpling_PhotosSelectorActivity.this);
        imageGrid.setAdapter(seletorAdapter);
        getSupportLoaderManager().initLoader(0, null, this);
        imageGrid.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {
                final Picasso picasso = Picasso.with(Dumpling_PhotosSelectorActivity.this);
                if (i == SCROLL_STATE_IDLE || i == SCROLL_STATE_TOUCH_SCROLL) {
                    picasso.resumeTag(Dumpling_PhotosSelectorActivity.this);
                } else {
                    picasso.pauseTag(Dumpling_PhotosSelectorActivity.this);
                }
            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {

            }
        });
    }

    @Override
    public void onAntiViolence(View view) {

    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        CursorLoader cursorLoader = new CursorLoader(this, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, STORE_IMAGES, null, null, STORE_IMAGES[2] + " DESC");
        return cursorLoader;
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        if (data != null) {
            final ArrayList<String> images = new ArrayList<String>();
            int count = data.getCount();
            if (count > 0) {
                data.moveToFirst();
                do {
                    String path = data.getString(data.getColumnIndexOrThrow(STORE_IMAGES[0]));
                    images.add(path);
                } while (data.moveToNext());
            }
            seletorAdapter.setDataList(images);
            seletorAdapter.setItemSize((getWindowManager().getDefaultDisplay().getWidth() - (3 * (getResources().getDimensionPixelOffset(R.dimen.px4)))) / 4);
            imageGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    if (i == 0) {
                        showCameraAction();
                    } else {
                        Uri imgUri = null;
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            //如果是7.0或以上
                            imgUri = FileProvider.getUriForFile(Dumpling_PhotosSelectorActivity.this, getApplicationContext().getPackageName() + ".fileprovider", new File(images.get(i - 1)));
                        } else {
                            imgUri = Uri.fromFile(new File(images.get(i - 1)));
                        }
                        openCrop(imgUri);
                    }
                }
            });
        }
    }

    /**
     * 打开Camera
     */
    private void showCameraAction() {
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (cameraIntent.resolveActivity(Dumpling_PhotosSelectorActivity.this.getPackageManager()) != null) {
            imageFile = Dumpling_FileUtils.createTempFile(Dumpling_PhotosSelectorActivity.this, Dumpling_SinoConstans.USER_ID);
            Uri imgUri = null;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                //如果是7.0或以上
                imgUri = FileProvider.getUriForFile(Dumpling_PhotosSelectorActivity.this, getApplicationContext().getPackageName() + ".fileprovider", imageFile);
            } else {
                imgUri = Uri.fromFile(imageFile);
            }
            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imgUri);
            startActivityForResult(cameraIntent, CAPTURE_CAMERA_REQUEST_CODE);
        } else {
            Toast.makeText(Dumpling_PhotosSelectorActivity.this, "No system camera found", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 裁剪图片
     *
     * @param imageUri 需要裁剪的图片Uri
     */
    private void openCrop(Uri imageUri) {
        imageFile = Dumpling_FileUtils.createTempFile(Dumpling_PhotosSelectorActivity.this, Dumpling_SinoConstans.USER_ID);
        Uri imgUri = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //如果是7.0或以上
            imgUri = FileProvider.getUriForFile(Dumpling_PhotosSelectorActivity.this, getApplicationContext().getPackageName() + ".fileprovider", imageFile);
        } else {
            imgUri = Uri.fromFile(imageFile);
        }
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(imageUri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("output", imgUri);
        intent.putExtra("aspectX", imageWidth);
        intent.putExtra("aspectY", imageHeight);
        startActivityForResult(intent, CAPTURE_PHOTO_REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Uri imgUri = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //如果是7.0或以上
            imgUri = FileProvider.getUriForFile(Dumpling_PhotosSelectorActivity.this, getApplicationContext().getPackageName() + ".fileprovider", imageFile);
        } else {
            imgUri = Uri.fromFile(imageFile);
        }
        if (CAPTURE_PHOTO_REQUEST_CODE == requestCode) {
            if (RESULT_OK == resultCode) {
                Intent resultData = new Intent();

                resultData.setData(imgUri);
                setResult(CAPTURE_PHOTO_RESULT_CODE, resultData);
                finish();
            }
        } else if (CAPTURE_CAMERA_REQUEST_CODE == requestCode) {
            if (RESULT_OK == resultCode) {
                openCrop(imgUri);
            }
        }
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {

    }


}
